package com.samcai.swiperecyclerview.view;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.ColorRes;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.OnItemTouchListener;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.samcai.swiperecyclerview.adapter.RecyclerViewAdapter;
import com.samcai.swiperecyclerview.divider.HorizontalDividerItemDecoration;
import com.samcai.swiperecyclerview.imp.RecyclerViewImp;
import com.samcai.swiperecyclerview.listener.OnItemClickListener;
import com.samcai.swiperecyclerview.listener.OnItemLongClickListener;
import com.samcai.swiperecyclerview.listener.OnItemScrollLeftListener;
import com.samcai.swiperecyclerview.listener.OnItemScrollRightListener;
import com.samcai.swiperecyclerview.listener.OnItemSelectedListener;
import com.samcai.swiperecyclerview.listener.OnLoadInRecyclerListener;
import com.samcai.swiperecyclerview.listener.OnSubItemClickListener;
import com.samcai.swiperecyclerview.listener.OnSwipeRefreshListener;


public class CustomRecyclerView extends RecyclerView implements RecyclerViewImp, OnItemTouchListener {

	/**
	 * HeaderView类型
	 */
	public final static int VIEW_TYPE_HEADER = 101;

	/**
	 * Footer类型
	 */
	public final static int VIEW_TYPE_FOOTER = 102;

	/**
	 * 加载状态View类型
	 */
	public final static int VIEW_TYPE_LOAD_STATE_VIEW = 103;

	private final static String TAG = "CustomRecyclerView";

	private final static String DefaultDecorationColor = "#b82169";

	private final static int DefaultDecorationSize = 1;

	private String loadStartText = "正在加载中";

	private String loadSucceedText = "点击加载更多";

	private String loadFailedText = "加载失败，点击重试";

	private String loadNoMoreText = "没有更多数据了";

	/**
	 * Item左划监听实例
	 */
	private OnItemScrollLeftListener mOnItemLeftScrollListener;

	/**
	 * Item右划监听实例
	 */
	private OnItemScrollRightListener mOnItemRightScrollListener;

	/**
	 * RecyclerView加载更多监听事件实例
	 */
	private OnLoadInRecyclerListener mOnLoadMoreListener;

	/**
	 * 监听侧滑事件
	 */
	private OnSwipeRefreshListener mOnSwipeRefreshListener;

	/**
	 * 分割线实例
	 */
	private ItemDecoration mItemDecoration;

	/**
	 * 在底部显示加载状态的ItemView
	 */
	private LoaderView mLoaderView;

	private Context mContext;

	/**
	 * HeaderView
	 */
	private View mHeaderView;

	/**
	 * FooterView
	 */
	private View mFooterView;

	/**
	 * 手指按下时所在的ItemView
	 */
	private View mTouched;

	/**
	 * 正在加载更多
	 */
	private boolean isLoading;

	/**
	 * 自动加载更多
	 */
	private boolean isAutoLoadMore = true;

	/**
	 * 没有更多了
	 */
	private boolean isNoMore;

	public CustomRecyclerView(Context context) {

		super(context);
		init(context);
	}

	public CustomRecyclerView(Context context, AttributeSet attrs) {

		super(context, attrs);
		init(context);
	}

	public CustomRecyclerView(Context context, AttributeSet attrs, int defStyle) {

		super(context, attrs, defStyle);
		init(context);
	}

	public boolean isLoading() {

		return isLoading;
	}

	@Override
	public void setOnItemClickListener(OnItemClickListener listener) {

		if (getAdapter() != null) {
			getAdapter().setOnItemClickListener(listener);
		}
	}

	@Override
	public void setOnItemLongClickListener(OnItemLongClickListener listener) {

		if (getAdapter() != null) {
			getAdapter().setOnItemLongClickListener(listener);
		}
	}

	@Override
	public void setOnItemSelectedListener(OnItemSelectedListener listener) {

		if (getAdapter() != null) {
			getAdapter().setOnItemSelectedListener(listener);
		}
	}

	@Override
	public void setOnItemLeftScrollListener(OnSwipeRefreshListener srListener, OnItemScrollLeftListener listener) {

		mOnItemLeftScrollListener = listener;
		addOnItemTouchListener(this);
		mOnSwipeRefreshListener = srListener;
	}

	@Override
	public void setOnItemRightScrollListener(OnSwipeRefreshListener srListener, OnItemScrollRightListener listener) {

		mOnItemRightScrollListener = listener;
		addOnItemTouchListener(this);
		mOnSwipeRefreshListener = srListener;
	}

	@Override
	public void setOnSubItemClickListener(int subViewId, OnSubItemClickListener listener) {

		if (getAdapter() != null) {
			getAdapter().setOnSubItemClickListener(subViewId, listener);
		}
	}

	@Override
	public void setOnLoadListener(OnLoadInRecyclerListener listener) {

		//
		mOnLoadMoreListener = listener;
		//
		mLoaderView = getDefaultLoadStateView();
		//
		if (listener != null && getAdapter() != null) {
			getAdapter().setLoaderView(mLoaderView);

		} else {
			mLoaderView = null;
			if (getAdapter() != null) {
				getAdapter().setLoaderView(null);
			}
		}
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void setAdapter(Adapter adapter) {

		super.setAdapter(adapter);
		if (getAdapter() != null) {
			getAdapter().setFooterView(mFooterView);
			getAdapter().setHeaderView(mHeaderView);
			getAdapter().setLoaderView(mLoaderView);
		}
	}

	@Override
	public void setHeaderView(View headerView) {

		if (getAdapter() != null) {
			getAdapter().setHeaderView(headerView);
		}
	}

	@Override
	public void setFooterView(View footerView) {

		if (getAdapter() != null) {
			getAdapter().setFooterView(footerView);
		}
	}

	@Override
	public View getHeaderView() {

		return mHeaderView;
	}

	@Override
	public View getFooterView() {

		return mFooterView;
	}

	@Override
	public LoaderView getLoadStateView() {

		return mLoaderView;
	}

	@Override
	public void removeHeaderView(View headerView) {

		mHeaderView = null;
		getAdapter().setHeaderView(null);
	}

	@Override
	public void removeFooterView(View footerView) {

		mFooterView = null;
		getAdapter().setFooterView(null);
	}

	@Override
	public void setItemDecoration(@ColorRes int color, int size, int leftMargin, int rightMargin) {

		if (size < 0) {
			return;
		}
		removeItemDecoration(mItemDecoration);
		mItemDecoration = new HorizontalDividerItemDecoration.Builder(mContext).color(color).size(size).margin(leftMargin, rightMargin)
				.build();
		addItemDecoration(mItemDecoration);
	}

	@Override
	public void setAutoLoadMoreEnable(boolean autoLoadMore) {

		isAutoLoadMore = autoLoadMore;
	}

	@Override
	public void setLoadStartText(String loadStartText) {

		this.loadStartText = loadStartText;
	}

	@Override
	public void setLoadSucceedText(String loadSucceedText) {

		this.loadSucceedText = loadSucceedText;
	}

	@Override
	public void setLoadFailedText(String loadFailedText) {

		this.loadFailedText = loadFailedText;
	}

	@Override
	public void setLoadNoMoreText(String loadNoMoreText) {

		this.loadNoMoreText = loadNoMoreText;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public RecyclerViewAdapter getAdapter() {

		Adapter adapter = super.getAdapter();
		if (adapter != null) {
			return (RecyclerViewAdapter) adapter;
		} else {
			return null;
		}
	}

	@Override
	public void succeed() {

		Log.d(TAG, "succeed");

		isLoading = false;
		isNoMore = false;
		if (mLoaderView != null) {
			mLoaderView.hideProgressBar();
			mLoaderView.setLoadingStateText(loadSucceedText);
		}
	}

	@Override
	public void failed() {

		Log.d(TAG, "failed");

		isLoading = false;
		if (mLoaderView != null) {
			mLoaderView.hideProgressBar();
			mLoaderView.setLoadingStateText(loadFailedText);
		}
	}

	@Override
	public void noMore() {

		Log.d(TAG, "noMore");

		isLoading = false;
		isNoMore = true;
		if (mLoaderView != null) {
			mLoaderView.hideProgressBar();
			mLoaderView.setLoadingStateText(loadNoMoreText);
		}
	}

	/**
	 * 初始化 设置布局管理器--setLayoutManager(manager) 这里设置为竖直方向排布
	 * 添加Item分隔符--addItemDecoration
	 */
	private void init(Context context) {

		//
		mContext = context;
		// 设置布局管理器
		LinearLayoutManager manager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
		setLayoutManager(manager);
		//
		mItemDecoration = new HorizontalDividerItemDecoration.Builder(context).color(Color.parseColor(DefaultDecorationColor))
				.size(DefaultDecorationSize).margin(0, 0).build();
		// 设置默认的分割线
		addItemDecoration(mItemDecoration);
		// 设置滑动监听
		setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

				if (!isLoading // 正在加载
						&& !isNoMore// 有更多
						&& mOnLoadMoreListener != null && isAutoLoadMore // 自动刷新
						&& isBottom()) {
					mOnLoadMoreListener.onLoad(CustomRecyclerView.this);
					loadStarted();
				}
			}
		});
	}

	/**
	 * 通知RecyclerView加载数据已开始
	 */
	private void loadStarted() {

		Log.d(TAG, "loadStarted");

		isLoading = true;
		if (mLoaderView != null) {
			mLoaderView.setLoadingStateText(loadStartText);
			mLoaderView.showProgressBar();
		}
	}

	/**
	 * 获得或者实例化一个底部加载状态的ItemView并返回
	 * 
	 * @return
	 */
	private LoaderView getDefaultLoadStateView() {

		if (mLoaderView == null) {
			mLoaderView = new LoaderView(mContext);
			mLoaderView.hideProgressBar();
		}
		return mLoaderView;
	}

	/**
	 * 最后一个Item已经在最底部返回True，反之False
	 */
	private boolean isBottom() {

		Log.d(TAG, "isBottom");

		LinearLayoutManager manager = (LinearLayoutManager) this.getLayoutManager();
		int position = manager.findLastCompletelyVisibleItemPosition();
		if (position == manager.getItemCount() - 1) {
			return true;
		}
		return false;
	}

	// ---OnItemTouchListener监听事件---

	private float viewX = -1;

	private float downX = -1;

	private float downY = -1;

	@Override
	public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent event) {

		//
		if (mOnItemLeftScrollListener == null && mOnItemRightScrollListener == null && mOnSwipeRefreshListener == null) {
			return false;
		}

		//
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			//
			View view = findChildViewUnder(event.getX(), event.getY());
			if (view != null) {
				viewX = view.getX();
				downX = event.getX();
				downY = event.getY();
				mTouched = view;
			}
		}

		//
		if (event.getAction() == MotionEvent.ACTION_MOVE) {
			//
			if (mTouched == null) {
				mOnSwipeRefreshListener.refreshEnable(true);
				return false;
			}

			//
			float curX = event.getX();
			float curY = event.getY();
			float mX = Math.abs(downX - curX);
			float mY = Math.abs(downY - curY);

			if (mX > mY) {
				// 根据XY轴滑动幅度判断是否是左右侧滑
				mOnSwipeRefreshListener.refreshEnable(false);
				return true;
			}
		}

		mOnSwipeRefreshListener.refreshEnable(true);
		return false;
	}

	@Override
	public void onTouchEvent(RecyclerView recyclerView, MotionEvent event) {

		float curX = event.getX();
		//
		if (event.getAction() == MotionEvent.ACTION_MOVE) {
			//
			if (mTouched == null) {
				return;
			}
			//
			float moveX = curX - downX;
			// 有监听才能拖动item
			if (moveX >= 0 && mOnItemRightScrollListener != null || moveX < 0 && mOnItemLeftScrollListener != null) {
				mTouched.setX(moveX);
			}
			return;
		}

		//
		if (event.getAction() == MotionEvent.ACTION_UP) {
			//
			if (mTouched == null) {
				return;
			}
			//
			int position = getChildPosition(mTouched) - (mHeaderView != null ? 1 : 0);
			if (position < 0) {
				return;
			}

			// 左滑
			if (downX - curX >= 0) {
				// 滑动长度大于三分之一才触发
				if (downX - curX >= getWidth() / 3 && mOnItemLeftScrollListener != null) {
					//
					mOnItemLeftScrollListener.onItemScrollLeft(mTouched, position, getAdapter().getData(position));
				}
			} else {// 右滑
				// 滑动长度大于三分之一才触发
				if (curX - downX >= getWidth() / 3 && mOnItemRightScrollListener != null) {
					//
					mOnItemRightScrollListener.onItemScrollRight(mTouched, position, getAdapter().getData(position));
				}
			}
			//
			if (mTouched != null) {
				mTouched.setX(viewX);
			}
		}
	}
	// --------------------------------

}
